/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.utils;

/**
 *
 * @author Rainbow
 * 
 * 自定义jedis连接池
 * 
 */
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisPoolUtils {
    
    public static JedisPoolConfig c = new JedisPoolConfig(); // 连接池配置
    public static JedisPool jedisPool = null; // 连接池
    
    static {
        c.setBlockWhenExhausted(true); // 连接耗尽则阻塞
        c.setLifo(true); // 后进先出
        c.setMaxIdle(10); // 最大空闲连接数为10
        c.setMinIdle(0); // 最小空闲连接数为0
        c.setMaxTotal(200); // 最大连接数为200
        c.setMaxWaitMillis(3); // 设置最大等待毫秒数：无限制
        c.setMinEvictableIdleTimeMillis(1800000); // 逐出连接的最小空闲时间：30分钟
        c.setTestOnBorrow(true); // 获取连接时是否检查连接的有效性：是
        c.setTestWhileIdle(true); // 空闲时是否检查连接的有效性：是

        jedisPool = new JedisPool(c, "127.0.0.1", 6379); // 初始化连接池
    }
    
    /**
     * 获取Jedis连接
     * @return Jedis连接
     */
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }
    
    public static void main(String[] args) {
        /* 操作Redis */
        Jedis jedis = null;
        try {
            jedis = JedisPoolUtils.getJedis();
            jedis.set("myname", "大黄");
            
            String s = jedis.get("1");
            String rs = jedis.get("myname");
            System.out.println(rs);
            System.out.println(s);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }
    
    public static void close(Jedis jedis)
    {
        try
        {
            jedisPool.returnResource(jedis);
        } catch (Exception e)
        {
            
        }
    }
    
    public static String getStatus()
    {
        return "Idle"+jedisPool.getNumIdle() + "\r\n" +
                "Active" + jedisPool.getNumActive() + "\r\n" +
                "Waiters" + jedisPool.getNumWaiters() + "\r\n" +
                "isClosed" + jedisPool.isClosed();
    }
    
    
    
    
    

}
